package jp.co.sharp.android.parents.kidsguard.activity.setting;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.bluetooth.parentble.ParentBleTransfer;

import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import jp.co.sharp.android.parents.kidsguard.App;
import jp.co.sharp.android.parents.kidsguard.R;
import jp.co.sharp.android.parents.kidsguard.activity.edit.AlarmActivity;
import jp.co.sharp.android.parents.kidsguard.activity.home.HomeActivity;
import jp.co.sharp.android.parents.kidsguard.activity.setting.adapter.PeriodSettingItemAdaptor;
import jp.co.sharp.android.parents.kidsguard.common.DateTimePickerDlg;
import jp.co.sharp.android.parents.kidsguard.common.DealWithWaitingDlg;
import jp.co.sharp.android.parents.kidsguard.common.ProcessWarningDlg;
import jp.co.sharp.android.parents.kidsguard.contants.Constants;
import jp.co.sharp.android.parents.kidsguard.contants.PageSerialNumConstants;
import jp.co.sharp.android.parents.kidsguard.contants.RequestMethodConstants;
import jp.co.sharp.android.parents.kidsguard.contants.RequestReceiverConstants;
import jp.co.sharp.android.parents.kidsguard.dto.BluetoothReceiverDto;
import jp.co.sharp.android.parents.kidsguard.dto.NotifyListDto;
import jp.co.sharp.android.parents.kidsguard.entity.KidInfoEntity;
import jp.co.sharp.android.parents.kidsguard.thread.BusinessThread;

/**
 * 通知期間の登録
 */
public class PeriodSettingAddActivity extends Activity {
    private App mApp;
    public ParentBleTransfer mParentBleTransfer;
    private String mNotifyList;
    private DealWithWaitingDlg mDealWithWaitingDlg;


    private KidInfoEntity mKidInfoEntity;
    private int mViewProcess = 0;
    private boolean mScreenOperate = false;

    private boolean mUnReceiver = true;
    private static final String TAG="TAG";

    // ページジャンプ
    private boolean mPageJumpFlag = false;
    // システムホームプレス
    private boolean mSystemHomeFlag = false;
    // プログラムロック
    private String mSyncLock = "syncLock";
    private final static int SUCCESS_CODE=200;
    private final static int PERIOD_SETTING_WEEK_REQUEST_CODE=3;

    private int repetition;
    private TextView mBeginTime ;
    private TextView mEndTime;
    private TextView mWeek;
    // 編集を再開しています...
    private boolean mEditReopening = false;
    private static final int PAGE_EDIT_REOPEN = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i(TAG,"PeriodSettingAddActivity_onCreate");
        setContentView(R.layout.activity_period_setting_add);
        getParamFromPeriodSetting();

        mApp = (App) getApplication();
        initReceiver();
        settingTimePicker();
        initListener();

    }
    @Override
    protected void onRestart() {
        super.onRestart();
        Log.i(TAG, "PowerSettingActivity_onRestart");
        synchronized (mSyncLock) {
            if (mSystemHomeFlag) {
                if (mApp.getAppStatus() != Constants.APP_STATUS_USER_PRESENT) {
                    Message msg = new Message();
                    msg.what = PAGE_EDIT_REOPEN;
                    handler.sendMessage(msg);
                }
                mSystemHomeFlag = false;
            }
        }

    }

    @Override
    protected void onStop() {
        Log.i(TAG,"PeriodSettingAddActivity_onStop");
        if (!mUnReceiver) {
            synchronized (mSyncLock) {
                try {
                    unregisterReceiver(receiver);
                } catch (IllegalArgumentException e) {
                    if (e.getMessage().contains("Receiver not registered")) {
                        // Ignore this exception. This is exactly what is desired
                        Log.e(TAG, e.getMessage());
                    } else {
                        // unexpected, re-throw
                        Log.e(TAG, e.getMessage());
                    }
                }
                if (mPageJumpFlag) {
                    try {
                        unregisterReceiver(systemReceiver);
                    } catch (IllegalArgumentException e) {
                        if (e.getMessage().contains("Receiver not registered")) {
                            // Ignore this exception. This is exactly what is desired
                            Log.e(TAG, e.getMessage());
                        } else {
                            // unexpected, re-throw
                            Log.e(TAG, e.getMessage());
                        }
                    }
                    mPageJumpFlag = false;
                }
            }
            mUnReceiver = true;
        }
        super.onStop();

    }

    @Override
    protected void onDestroy() {
        Log.i(TAG,"PeriodSettingAddActivity_onDestroy");
        if (!mUnReceiver) {
            synchronized (mSyncLock) {
                try {
                    unregisterReceiver(receiver);
                } catch (IllegalArgumentException e) {
                    if (e.getMessage().contains("Receiver not registered")) {
                        // Ignore this exception. This is exactly what is desired
                        Log.e(TAG, e.getMessage());
                    } else {
                        // unexpected, re-throw
                        Log.e(TAG, e.getMessage());
                    }
                }
                if (mPageJumpFlag) {
                    try {
                        unregisterReceiver(systemReceiver);
                    } catch (IllegalArgumentException e) {
                        if (e.getMessage().contains("Receiver not registered")) {
                            // Ignore this exception. This is exactly what is desired
                            Log.e(TAG, e.getMessage());
                        } else {
                            // unexpected, re-throw
                            Log.e(TAG, e.getMessage());
                        }
                    }
                    mPageJumpFlag = false;
                }
            }
            mUnReceiver = true;
        }
        super.onDestroy();
    }

    /**
     * ページリターンキー、フルスクリーンリターンジェスチャー
     */
    @Override
    public void onBackPressed() {
        Log.i(TAG,"DeviceSelectorActivity_onBackPressed");
        backView();
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.i(TAG, "DeviceSelectorActivity_onStart");
        mApp.setAppStatus(Constants.APP_STATUS_INIT);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i(TAG, "PeriodSettingActivity_onActivityResult");
        initReceiver();
        if (resultCode == SUCCESS_CODE) {
            if (requestCode == PERIOD_SETTING_WEEK_REQUEST_CODE) {
                TextView textView = findViewById(R.id.week);
               repetition =  data.getIntExtra("repetition",-1);
               if(0 != repetition){
                   Set<String> weekStr =  PeriodSettingWeekActivity.repetitionToHex16String(repetition);
                   textView.setText(weekStr.toString());
               }else{
                   textView.setText("1回のみ");
               }
            }
        }
    }

    public void getParamFromPeriodSetting() {
        Log.i(TAG,"PeriodSettingAddActivity_getParamFromPeriodSetting");
        Intent intent = getIntent();
        mNotifyList = intent.getStringExtra("notifyListDtoList");
    }

    public void initListener() {
        Log.i(TAG,"PeriodSettingAddActivity_backView");
        ImageView imageView = findViewById(R.id.backView);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               backView();
            }
        });

        LinearLayout linearLayout = findViewById(R.id.weekLayout);
        linearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(PeriodSettingAddActivity.this,PeriodSettingWeekActivity.class);
//                if(repetition == -1){repetition = 0; }
                intent.putExtra("repetition",repetition);
                TextView textView = findViewById(R.id.week);
                startActivityForResult(intent,PERIOD_SETTING_WEEK_REQUEST_CODE);
            }
        });

        mBeginTime = findViewById(R.id.beginTime);
        mEndTime = findViewById(R.id.endTime);
        mWeek = findViewById(R.id.week);
        defaultTime();
    }

    public void defaultTime(){
        Date date = new Date();
        SimpleDateFormat df = new SimpleDateFormat("HH:mm");
        mBeginTime.setText(PeriodSettingActivity.formatTime(df.format(date)));
        mEndTime.setText(PeriodSettingActivity.formatTime(df.format(date)));

        String[] weeks = {"40","01","02","04","08","10","20"};
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0){
            w = 0;
        }
        repetition = Integer.parseInt(weeks[w]);
        List<String> strings = AlarmActivity.repetitionToStirng(weeks[w]);
        mWeek.setText(strings.get(0).toString());
    }

    public void formatWeekNum(){

    }

    public void backView(){
        NotifyListDto notifyDto = new NotifyListDto();
        notifyDto.setBeginTime((String)mBeginTime.getText());
        notifyDto.setEndTime((String)mEndTime.getText());
        notifyDto.setWeekday(repetition);
        notifyDto.setState(0);
        notifyDto.setNo(-1);

        Intent intent = new Intent(PeriodSettingAddActivity.this, PeriodSettingActivity.class);
        intent.putExtra("notifyDto", notifyDto);
        setResult(SUCCESS_CODE, intent);//200代表成功
        mPageJumpFlag=true;
        finish();
    }


    public int[] formatTimeToNum(String time){
        String str = time.substring(2);
        String[] split = str.split(":");

        Integer pAmPm = 0;
        Integer pHour = Integer.parseInt(split[0]);
        if(time.substring(0,2).equals("午後")){
            pAmPm=1;
        };
        int[] timeNum = new int[3];
        timeNum[0]=pAmPm;
        timeNum[1]=pHour;
        timeNum[2]=Integer.parseInt(split[1]);
        return timeNum;
    }

    public void showTimePickerDlg(String time) {
        Log.i(TAG,"PeriodSettingAddActivity_showTimePickerDlg");
        int viewId = getResources().getIdentifier(time, "id", getPackageName());
        TextView textView = findViewById(viewId);
        int[] num = formatTimeToNum((String) textView.getText());
        System.out.println(num[1]+","+num[2]);


        DateTimePickerDlg dateTimePickerDlg = new DateTimePickerDlg(this, R.style.dateTimePicker, num[0], num[1], num[2]);
        dateTimePickerDlg.setOnDateTimeSetListener(new DateTimePickerDlg.OnDateTimeSetListener() {
            @Override
            public void onDateTimeSet(int pAmPm, int pHour, int pMinute) {

                String pm = "";
                String hour =  pHour+"";
                String min =pMinute+"";
                if (pAmPm == 0) {
                    pm = "午前";
                } else {
                    pm = "午後";
                }
                if (pHour < 10) {
                    hour = "0" + pHour;
                }
                if (pMinute < 10) {
                    min = "0" + pMinute;
                }
                textView.setText(pm+hour+":"+min);
            }
        });
        dateTimePickerDlg.show();
    }

    public void settingTimePicker() {
        Log.i(TAG,"PeriodSettingAddActivity_settingTimePicker");
        // 监听
        TextView mStartTime = findViewById(R.id.beginTime);
        mStartTime.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                    String time = "beginTime";
                    showTimePickerDlg(time);
                    return true;
                }
                return false;
            }
        });
        mStartTime.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (b) {
                    String time = "beginTime";
                    showTimePickerDlg(time);
                }
            }
        });

        TextView endTime = findViewById(R.id.endTime);
        endTime.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    String time = "endTime";
                    showTimePickerDlg(time);
                    return true;
                }
                return false;
            }
        });
        endTime.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    String time = "endTime";
                    showTimePickerDlg(time);
                }
            }
        });
    }

    public void initReceiver() {
        Log.i(TAG,"PeriodSettingAddActivity_initReceiver");
        mKidInfoEntity = ((App) getApplication()).findKidInfoBySelect();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        filter.addAction(Intent.ACTION_USER_PRESENT);
        // ホームボタン
        filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_CONNECT_STATE_CHANGED);
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_WRITE_DATA_CHANGED);
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED);
        registerReceiver(receiver, filter);
        registerReceiver(systemReceiver, filter);
        this.mParentBleTransfer = ((App)getApplication()).getmParentBleTransfer();
        mUnReceiver = false;
    }
    /**
     * システム放送
     */
    private final BroadcastReceiver systemReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                String action = intent.getAction();
                if (Intent.ACTION_SCREEN_OFF.equals(action)) {
                    synchronized (mSyncLock) {
                        mApp.setAppStatus(Constants.APP_STATUS_INIT);
                        mScreenOperate = true;
                        mViewProcess = Constants.SEND_KID_EXIT;
                    }

                } else if (Intent.ACTION_USER_PRESENT.equals(action)) {
                    synchronized (mSyncLock) {
                        mApp.setAppStatus(Constants.APP_STATUS_USER_PRESENT);
                        if (!mPageJumpFlag) {
                            Message msg = new Message();
                            msg.what = PAGE_EDIT_REOPEN;
                            handler.sendMessage(msg);
                        }
                    }
                } else if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {
                    synchronized (mSyncLock) {
                        mApp.setAppStatus(Constants.APP_STATUS_INIT);
                        mSystemHomeFlag = true;
                        mScreenOperate = true;
                        mViewProcess = Constants.SEND_KID_EXIT;
                        new BusinessThread(Constants.SEND_KID_EXIT,
                                mParentBleTransfer,
                                mKidInfoEntity,
                                null,
                                PageSerialNumConstants.PAGE_SERTAL_NUM_OKAERI_NOTIFICATION).start();
                    }

                }else if (RequestReceiverConstants.RECEIVER_BLUETOOTH_CONNECT_STATE_CHANGED.equals(action)) {
                    // 初期化
                    BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                    String macAddress = bluetoothReceiverDto.getAddress();
                    if (mApp.isMimamoriCheck(macAddress)) {
                        mApp.addmLsIsMimamori(macAddress);
                        // TODO Mimamori
                        mViewProcess = Constants.SEND_KID_EXIT;
                        new BusinessThread(Constants.SEND_KID_EXIT,
                                mParentBleTransfer,
                                mKidInfoEntity,
                                null,
                                PageSerialNumConstants.PAGE_SERTAL_NUM_OKAERI_NOTIFICATION).start();
                        // ページジャンプ
                        mPageJumpFlag = true;
                        Intent intent1 = new Intent();
                        intent1.setAction(Constants.ACTION_IS_MIMAMORI);
                        intent1.setClass(PeriodSettingAddActivity.this, HomeActivity.class);
                        startActivity(intent1);
                    }else {
                        mKidInfoEntity.setBtConnStatus(Constants.DEVICE_DISCONNECTION_SUCCESS);
                        mApp.updateKidInfo(mKidInfoEntity);

                        String message = mKidInfoEntity.getKidName() + "と切断されました。編集を中断します。";
                        ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(PeriodSettingAddActivity.this, R.style.commonDlg, message);
                        processWarringDlg.show();
                        processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                            @Override
                            public void onOperateSet() {
                                processWarringDlg.dismiss();
                                // ページジャンプ
                                mPageJumpFlag = true;
                                Intent intent1 = new Intent();
                                intent1.setClass(PeriodSettingAddActivity.this, SettingActivity.class);
                                startActivity(intent1);
                            }
                        });
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, e.getMessage());
            }
        }
    };
    /**
     * BroadcastReceiver
     */
    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i(TAG,"PeriodSettingAddActivity_BroadcastReceiver");
            try {
                String action = intent.getAction();
                if (RequestReceiverConstants.RECEIVER_BLUETOOTH_WRITE_DATA_CHANGED.equals(action)) {
                    BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                    if (bluetoothReceiverDto.isFinished()) {
                        switch (mViewProcess) {
                            case Constants.SEND_KID_ENTER:
                                mViewProcess = Constants.SEND_KID_GET_INFO;
                                if (mScreenOperate) {
                                    mEditReopening = false;
                                    mScreenOperate = false;
                                    handler.sendEmptyMessage(0);
                                }
                                break;
                            case Constants.SEND_KID_EXIT:
                                if (mDealWithWaitingDlg != null && mDealWithWaitingDlg.isShowing()) {
                                    mDealWithWaitingDlg.dismiss();
                                }
                                if (!mScreenOperate) {
                                    // ページジャンプ
                                    mPageJumpFlag = true;
                                    PeriodSettingAddActivity.this.finish();
                                }
                                break;
                        }
                    }
                } else if ( RequestReceiverConstants.RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED.equals(action)) {
                    BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                    String retStr = bluetoothReceiverDto.getRetStr();
                    JSONObject jsonObject = new JSONObject(retStr);
                    if (RequestMethodConstants.METHOD_GET_OPERATING_STATE.equals(jsonObject.getString("method"))) {
                        JSONObject data = jsonObject.getJSONObject("data");
                        if (Constants.IS_USING_OK.equals(data.getString("state"))) {
                            //send enter
                            mViewProcess = Constants.SEND_KID_ENTER;
                            new BusinessThread(Constants.SEND_KID_ENTER, PageSerialNumConstants.PAGE_SERTAL_NUM_OKAERI_NOTIFICATION, mParentBleTransfer, mKidInfoEntity).start();
                        } else {
                            mDealWithWaitingDlg.dismiss();
                            String message = "別のスマートフォンから操作中のため、設定を変更できません。";
                            ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(PeriodSettingAddActivity.this, R.style.commonDlg, message);
                            processWarringDlg.show();
                            processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                                @Override
                                public void onOperateSet() {
                                    processWarringDlg.dismiss();
                                    mPageJumpFlag=true;
                                    PeriodSettingAddActivity.this.finish();
                                }
                            });
                        }
                    } else if (RequestMethodConstants.METHOD_ON_SYNC_RESULT.equals(jsonObject.getString("method"))) {
                        if (Constants.ON_SYNC_RESULT.equals(jsonObject.getString("result"))) {
                            // ページジャンプ
                            mPageJumpFlag = true;
                        }
                    } else if (RequestMethodConstants.METHOD_ON_OPERATE_INTERRUPT.equals(jsonObject.getString("method"))) {
                        String message = "キッズケータイが操作されました。編集を中断します。";
                        ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(PeriodSettingAddActivity.this, R.style.commonDlg, message);
                        processWarringDlg.show();
                        processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                            @Override
                            public void onOperateSet() {
                                mPageJumpFlag = true;
                                Intent intent1 = new Intent(PeriodSettingAddActivity.this,SettingActivity.class);
                                startActivity(intent1);
                                processWarringDlg.dismiss();
                            }
                        });
                    }
                }
            } catch (Exception e) {
                Log.e(TAG,e.getMessage());
//                e.printStackTrace();
            }
        }
    };

    /**
     * Dialog閉じる
     */
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (null != mDealWithWaitingDlg && mDealWithWaitingDlg.isShowing()) {
                mDealWithWaitingDlg.dismiss();
            } else if (msg.what == PAGE_EDIT_REOPEN) {
                if (!mEditReopening) {
                    String message = "編集を再開しています...";
                    mDealWithWaitingDlg = new DealWithWaitingDlg(PeriodSettingAddActivity.this, R.style.commonDlg, message, false);
                    mDealWithWaitingDlg.show();
                    mScreenOperate = true;
                    mViewProcess = Constants.SEND_KID_IS_USING;
                    new BusinessThread(Constants.SEND_KID_IS_USING,
                            mParentBleTransfer,
                            mKidInfoEntity,
                            null,
                            PageSerialNumConstants.PAGE_SERIAL_NUM_POWER_SETTING).start();
                    // ブロードキャストの再登録
                    unregisterReceiver(systemReceiver);
                    initReceiver();
                    mEditReopening = true;
                }
            }
        }
    };



}
